/**
 * 
 */
package com.laozhao.dreamframe.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Properties;

/**
 * @author dozhao
 * 
 */
public class ViewMetaConfig {

	private static ViewMetaConfig config;

	private String fileName = "ViewMetaConfig.ini";
	private Properties ini = new Properties();

	//
	// private int bufferSize = 200;
//	private Map<String, String> bufferMap;

	private ViewMetaConfig() {
		try {
			File iniFile = new File(fileName);
			if (!iniFile.exists()) {
				iniFile.createNewFile();
			}
			ini.load(new FileInputStream(iniFile));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static ViewMetaConfig getInstance() {
		if (config == null) {
			config = new ViewMetaConfig();
		}
		return config;
	}

	/**
	 * 读取INI信息
	 */
	public String getIniValue(String key) {
		if (ini.containsKey(key)) {
			return ini.getProperty(key);
		} else {
//			if (!bufferMap.containsKey(key)) {
//				bufferMap.put(key,"");
//				ini.put(key, "");
				saveIni(key);
//			}
//			return bufferMap.get(key);
				return null;
		}
	}
	/**
	 * 读取INI信息
	 */
	public <E> E getIniValue(String key , Class<E> clazz) {
		E value = null;
		if (getIniValue(key) == null) {
			return null;
		}
		try {
			value = clazz.cast(getIniValue(key));
		} catch (ClassCastException  e) {
			e.printStackTrace();
			return null;
		}		
		return value;		
	}

	/**
	 * 保存INI信息
	 */
	private void saveIni(String key) {
		try {
			Writer fw = new FileWriter(new File(fileName), true);
			BufferedWriter bw = new BufferedWriter(fw);
			// for (int i = 0; i < k.length; i++) {
			bw.write(key + "\t=\t" );
			bw.newLine();
			// }
			bw.close();
			// if (bufferMap.size() > bufferSize) {
			// fw.flush();
			// ini.load(new FileInputStream(new File(fileName)));
			// bufferMap.clear();
			// }
			fw.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
